﻿import psycopg2

db = psycopg2.connect(host='pg-utf.sweb.ru', database='artsunorg', user='artsunorg', password='Rheptyinthy359', charset='utf-8')

def query_db(query, args=(), one=False):
    """Queries the database and returns a list of dictionaries."""
    cur = db.cursor()
    cur.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv

def query_db2(query, args=(), one=False):
    """Queries the database and returns a list of dictionaries."""
    cur = db.cursor()
    cur.execute(query, args)
    rv = list()
    d = dict()
    for row in cur.fetchall():
        d.clear()
        for idx, value in enumerate(row):
            #if isinstance(value, (str, unicode)):
            #    value = value.decode('utf-8')
            d[cur.description[idx][0]] = value
        if d:
            rv.append(dict(**d))

    return (rv[0] if rv else None) if one else rv

'''
cur = db.cursor()
cur.execute('select id, title from state where id > %s', (0,))
rows = cur.fetchall()
one = False
rv = [dict((cur.description[idx][0], value) for idx, value in enumerate(row)) for row in rows]
print (rv[0] if rv else None) if one else rv
'''

print query_db2('select id, title from issue where id > %s', (0,))